<template>
  <div>
    <div class="gva-search-box">
      <el-form :inline="true" :model="searchInfo" class="demo-form-inline" @keyup.enter="onSubmit">
      <el-form-item label="创建时间">
      <el-date-picker v-model="searchInfo.startCreatedAt" type="datetime" placeholder="开始时间"></el-date-picker>
       —
      <el-date-picker v-model="searchInfo.endCreatedAt" type="datetime" placeholder="结束时间"></el-date-picker>
      </el-form-item>
        <el-form-item label="实验名称">
         <el-input v-model="searchInfo.symc" placeholder="搜索条件" />

        </el-form-item>
        <el-form-item label="实验时间">
            
            <el-date-picker v-model="searchInfo.startSysj" type="datetime" placeholder="搜索条件（起）"></el-date-picker>
            —
            <el-date-picker v-model="searchInfo.endSysj" type="datetime" placeholder="搜索条件（止）"></el-date-picker>

        </el-form-item>
        <el-form-item label="实验完成人">
         <el-input v-model="searchInfo.sywcr" placeholder="搜索条件" />

        </el-form-item>
        <el-form-item label="实验文件">
         <el-input v-model="searchInfo.sywj" placeholder="搜索条件" />

        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
        <div class="gva-btn-list">
            <el-button type="primary" icon="plus" @click="openDialog">新增</el-button>
            <el-button type="primary" icon="plus" @click="openDialog2">批量导入</el-button>
            <!-- ================================以下为导入新增===================================== -->
            <!-- <el-upload
              action=""
              :before-upload="checkFile"
              :on-error="uploadError"
              :on-success="uploadSuccess"
              :on-change="handleChange"
              :show-file-list="false"
              class="upload-btn"
              >
              <el-button size="small" style="margin-left: 10px;" type="primary">导入</el-button>
            </el-upload>
            <el-button size="small" style="margin-left: 10px;" type="primary" @click="getExcelTemplate">下载导入模板</el-button> -->
            <!-- ================================以上为导入新增===================================== -->
            <!-- <batchImport style="margin-left: 10px"></batchImport> -->
            <!-- ================================以下为导出新增===================================== -->
            <el-button style="margin-left: 10px;" type="primary" @click="GetCityList">导出</el-button>
            <!-- //json_data为数据源List，json_fields为表头信息和取值逻辑 -->
            <!-- <el-button  size="small" style="margin-left: 10px;" type="primary" data="json_data" fields="json_fields">点击导出</el-button> -->
            <!-- ================================以上为导出新增===================================== -->
            <el-popover v-model:visible="deleteVisible" placement="top" width="160">
            <p>确定要删除吗？</p>
            <div style="text-align: right; margin-top: 8px;">
                <el-button type="primary" link @click="deleteVisible = false">取消</el-button>
                <el-button type="primary" @click="onDelete">确定</el-button>
            </div>
            <template #reference>
                <el-button icon="delete" style="margin-left: 10px;" :disabled="!multipleSelection.length" @click="deleteVisible = true">删除</el-button>
            </template>
            </el-popover>
        </div>
        <el-table
        ref="multipleTable"
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        row-key="ID"
        @selection-change="handleSelectionChange"
        @sort-change="sortChange"
        >
        <el-table-column type="selection" width="55" />
        <el-table-column align="left" label="日期" width="180">
            <template #default="scope">{{ formatDate(scope.row.CreatedAt) }}</template>
        </el-table-column>
        <el-table-column sortable align="left" label="样本数据ID" prop="ybsjid" width="120" />
        <el-table-column align="left" label="实验名称" prop="symc" width="120" />
         <el-table-column align="left" label="实验时间" width="180">
            <template #default="scope">{{ formatDate(scope.row.sysj) }}</template>
         </el-table-column>
        <el-table-column align="left" label="实验完成人" prop="sywcr" width="120" />
        <el-table-column align="left" label="实验文件" prop="sywj" width="120" />
        <el-table-column align="left" label="按钮组">
            <template #default="scope">
            <el-button type="primary" link icon="edit" class="table-button" @click="updateSampleDataFunc(scope.row)">变更</el-button>
            <el-button type="primary" link icon="delete" @click="deleteRow(scope.row)">删除</el-button>
            </template>
        </el-table-column>
        </el-table>
        <div class="gva-pagination">
            <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            />
        </div>
    </div>
    <el-dialog v-model="dialogFormVisible" :before-close="closeDialog" title="">
      <el-form :model="formData" label-position="right" ref="elFormRef" :rules="rule" label-width="80px">
        <el-form-item label="样本数据ID:"  prop="ybsjid" >
          <el-input v-model.number="formData.ybsjid" :clearable="true" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="实验名称:"  prop="symc" >
          <el-input v-model="formData.symc" :clearable="true"  placeholder="请输入" />
        </el-form-item>
        <el-form-item label="实验时间:"  prop="sysj" >
          <el-date-picker v-model="formData.sysj" type="date" style="width:100%" placeholder="选择日期" :clearable="true"  />
        </el-form-item>
        <el-form-item label="实验完成人:"  prop="sywcr" >
          <el-input v-model="formData.sywcr" :clearable="true"  placeholder="请输入" />
        </el-form-item>
        <el-form-item label="实验文件:"  prop="sywj" >
          <el-input v-model="formData.sywj" :clearable="true"  placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="enterDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>
<!-- ====================================以下为录入弹窗==================================== -->
    <!-- <el-dialog v-model="dialogFormVisible2" :before-close="closeDialog2" title="录入数据弹窗操作">
      <el-form :model="formData" label-position="right" ref="elFormRef" :rules="rule" label-width="80px">
        <el-form-item label="样本ID:"  prop="ybsjid" >
          <el-input v-model.number="formData.ybsjid" :clearable="true" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="实验名称:"  prop="symc" >
          <el-input v-model="formData.symc" :clearable="true"  placeholder="请输入" />
        </el-form-item>
        <el-form-item label="实验时间:"  prop="sysj" >
          <el-date-picker v-model="formData.sysj" type="date" style="width:100%" placeholder="选择日期" :clearable="true"  />
        </el-form-item>
        <el-form-item label="实验人:"  prop="sywcr" >
          <el-input v-model="formData.sywcr" :clearable="true"  placeholder="请输入" />
        </el-form-item>
    <el-form-item label="实验文件:"  prop="sywj" >
      <el-input v-model="formData.sywj" :clearable="true"  placeholder="请输入" />
    </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog2">取 消</el-button>
          <el-button type="primary" @click="ensureImport">确 定</el-button>
        </div>
      </template>
    
    </el-dialog> -->

<!-- ====================================以上为录入弹窗==================================== -->
<!-- ==========================以下为导入时弹出模板提示============================================ -->
<el-dialog v-model="dialogFormVisible2" :before-close="closeDialog2" title="">
      <!-- <el-form :model="formData" label-position="right" ref="elFormRef" :rules="rule" label-width="120px"> -->
        <!-- <el-form-item label="文件要求xlsx格式：['样本数据ID', '实验名称', '实验时间', '实验完成人', '实验文件']" text-align:center> -->
        <el-form-item label="请上传xlsx格式文件" text-align:center>
          <!-- <el-input v-model.number="formData.cZPTID" :clearable="true" placeholder="请输入" /> -->
        </el-form-item>
        <el-button size="small" style="margin-left: 300px;margin-bottom: 10px;" type="primary" @click="getExcelTemplate">下载模板</el-button>

        <el-upload
              action=""
              :before-upload="checkFile"
              :on-error="uploadError"
              :on-success="uploadSuccess"
              :on-change="handleChange"
              :file-list="fileList"
              class="upload-btn"
              >
              <el-button size="small" style="margin-left: 300px" type="primary">直接导入</el-button>
        </el-upload>
            
      <!-- </el-form> -->
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="closeDialog2">取 消</el-button>
          <el-button size="small" type="primary" @click="ensureImport">确 定</el-button>
        </div>
      </template>
    </el-dialog>
<!-- ==========================以上为导入时弹出模板提示============================================ -->

  </div>
</template>

<script>
export default {
  name: 'SampleData'
}
</script>

<script setup>
import {
  createSampleData,
  deleteSampleData,
  deleteSampleDataByIds,
  updateSampleData,
  findSampleData,
  findByIds,
  getSampleDataList
} from '@/api/sampleData'
//=================================以下为导入导出新加内容===================================
//excel文件数据解析
import * as XLSX from 'xlsx/xlsx.js'

//引入导出excel组件方法
import * as export_json_to_excel from '@/api/Export2Excel.js'

//=================================以上为导入导出新加内容===================================

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, formatBoolean, filterDict } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive } from 'vue'

//============以下为上传新增==============
import { useUserStore } from '@/pinia/modules/user'
import { async } from 'q'
const emit = defineEmits(['on-success'])
const path = ref(import.meta.env.VITE_BASE_API)
const userStore = useUserStore()
const fullscreenLoading = ref(false)
//============以上为上传新增==============
// 自动化生成的字典（可能为空）以及字段
const formData = ref({
        ybsjid: 0,
        symc: '',
        sysj: new Date(),
        sywcr: '',
        sywj: '',
        })

// 验证规则
const rule = reactive({
})

const elFormRef = ref()


// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})
// 排序
const sortChange = ({ prop, order }) => {
  searchInfo.value.sort = prop
  searchInfo.value.order = order
  getTableData()
}

// 重置
const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

// 搜索
const onSubmit = () => {
  page.value = 1
  pageSize.value = 10
  getTableData()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查询
const getTableData = async() => {
  const table = await getSampleDataList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async () =>{
}

// 获取需要的字典 可能为空 按需保留
setOptions()


// 多选数据
const multipleSelection = ref([])
// 多选
const handleSelectionChange = (val) => {
    multipleSelection.value = val
}

// 删除行
const deleteRow = (row) => {
    ElMessageBox.confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
            deleteSampleDataFunc(row)
        })
    }


// 批量删除控制标记
const deleteVisible = ref(false)

// 多选删除
const onDelete = async() => {
      const ids = []
      if (multipleSelection.value.length === 0) {
        ElMessage({
          type: 'warning',
          message: '请选择要删除的数据'
        })
        return
      }
      multipleSelection.value &&
        multipleSelection.value.map(item => {
          ids.push(item.ID)
        })
      const res = await deleteSampleDataByIds({ ids })
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
        if (tableData.value.length === ids.length && page.value > 1) {
          page.value--
        }
        deleteVisible.value = false
        getTableData()
      }
    }

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')

// 更新行
const updateSampleDataFunc = async(row) => {
    const res = await findSampleData({ ID: row.ID })
    type.value = 'update'
    if (res.code === 0) {
        formData.value = res.data.resampleData
        dialogFormVisible.value = true
    }
}


// 删除行
const deleteSampleDataFunc = async (row) => {
    const res = await deleteSampleData({ ID: row.ID })
    if (res.code === 0) {
        ElMessage({
                type: 'success',
                message: '删除成功'
            })
            if (tableData.value.length === 1 && page.value > 1) {
            page.value--
        }
        getTableData()
    }
}


// 弹窗控制标记
const dialogFormVisible = ref(false)

// 打开弹窗
const openDialog = () => {
    type.value = 'create'
    dialogFormVisible.value = true
}

// 关闭弹窗
const closeDialog = () => {
    dialogFormVisible.value = false
    formData.value = {
        ybsjid: 0,
        symc: '',
        sysj: new Date(),
        sywcr: '',
        sywj: '',
        }
}
// 弹窗确定
const enterDialog = async () => {
     elFormRef.value?.validate( async (valid) => {
             if (!valid) return
              let res
              switch (type.value) {
                case 'create':
                  res = await createSampleData(formData.value)
                  break
                case 'update':
                  res = await updateSampleData(formData.value)
                  break
                default:
                  res = await createSampleData(formData.value)
                  break
              }
              if (res.code === 0) {
                ElMessage({
                  type: 'success',
                  message: '创建/更改成功'
                })
                closeDialog()
                getTableData()
              }
      })
}

//=============================以下为批量导入弹窗=================================
//批量导入弹窗控制标记
const dialogFormVisible2=ref(false)
//打开批量导入弹窗
const openDialog2 = () => {
    dialogFormVisible2.value = true
}
//关闭批量导入弹窗
const closeDialog2 = () => {
    dialogFormVisible2.value = false
}
//=============================以上为批量导入弹窗=================================

// =======================================以下导入为新增==============================================
const arr=[]
const fileList=[]
const handleChange=(file)=>{
  fileList.push({name:file.name});  
  importfxx(file.raw);
}
 const importfxx=(obj) =>{
  var rABS = false; //是否将文件读取为二进制字符串
  var f=obj;
            var reader = new FileReader();
            
            FileReader.prototype.readAsBinaryString = function(f) {
                var binary = "";
                var rABS = false; //是否将文件读取为二进制字符串
                var pt = this;
                var wb; //读取完成的数据
                var outdata;
                var reader = new FileReader();
                reader.onload = function(e) {
                    var bytes = new Uint8Array(reader.result);
                    var length = bytes.byteLength;
                    for (var i = 0; i < length; i++) {
                        binary += String.fromCharCode(bytes[i]);
                    }
                    //var XLSX = require("xlsx");
                    if (rABS) {
                        wb = XLSX.read(btoa(fixdata(binary)), {
                        //手动转化
                        type: "base64"
                        });
                    } else {
                        wb = XLSX.read(binary, {
                        type: "binary"
                        });
                    }
                    outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); //outdata就是你想要的东西
                    //此处可对数据进行处理
                    
                    outdata.map(async v => {
                        //============================数据转换开始==========================
                        let temp = ref({
                          // ybsjid: 0,
                          // symc: '',
                          // sysj: new Date(),
                          // sywcr: '',
                          // sywj: '',
                        })
                        
                        temp.value = {
                          ybsjid: v['样本数据ID'],
                          symc: v['实验名称'],
                          sysj: v['实验时间'],
                          sywcr: v['实验完成人'],
                          sywj: v['实验文件'],
                        }
                        arr.push(temp)

                    });
                };
                reader.readAsArrayBuffer(f);
            };
            if (rABS) {
                reader.readAsArrayBuffer(f);
            } else {
                reader.readAsBinaryString(f);
            }

}

const ensureImport=()=>{
  arr.forEach(async (formData)=>{
    let res = await createSampleData(formData.value);
  })
  // console.log('arr中数据如下：');
  // console.log(arr);
  closeDialog2();
  setTimeout(()=>{
    getTableData();
  },500);
            
  ElMessage({
    type: 'success',
    message: '导入成功'
  })
  //arr=[]
}
// =======================================以上导入为新增==============================================


const checkFile = (file) => {
  fullscreenLoading.value = true
  const isExcel = file.type === "application/vnd.ms-excel";
  const isXML = file.type === "text/xml";
  const isLt2M = file.size / 1024 / 1024 < 0.5
  if (!isExcel && !isXML) {
    this.$message.error("只能上传Excel或XML文件");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('上传文件大小不能超过 500KB')
    fullscreenLoading.value = false
  }
  return  isLt2M
}

const uploadSuccess = (res) => {
  const { data } = res
  if (data.file) {
    emit('on-success', data.file.url)
  }
}

const uploadError = () => {
  ElMessage({
    type: 'error',
    message: '上传失败'
  })
  fullscreenLoading.value = false
}

// =======================================以下为导出新增==============================================

//格式化
const formatJson=(filterVal, jsonData)=> {
  return jsonData.map(v => filterVal.map(j => v[j]))
};
          //获取城镇数据
         const GetCityList=async()=>{
            //===================以下为导出所有的数据===========================
            if (multipleSelection.value.length === 0) {
              ElMessage({
                type: 'warning',
                message: '默认导出所有数据'
              })
  
              const table =await getSampleDataList({})
              const ExportList = ref([]);

              ExportList.value = table.data.list
              getExcel_city(ExportList.value);
              return
            }
            
            if (multipleSelection.value.length === 0) {
              ElMessage({
                type: 'warning',
                message: '请选择要导出的数据'
              })
              return
            }
            const ids = []
            multipleSelection.value &&
            multipleSelection.value.map(item => {
              ids.push(item.ID)
            })
            const table = await findByIds({ ids })
            //===================以上为导出所有的数据===========================
            const ExportList = ref([]);

            ExportList.value = table.data.list
            getExcel_city(ExportList.value);
          };
          //导出城镇方法
        const getExcel_city=(res)=> {
                  const tHeader = ['样本数据ID', '实验名称', '实验时间', '实验完成人', '实验文件']
                  const filterVal = ['ybsjid', 'symc', 'sysj', 'sywcr', 'sywj']
                  const list = res
                  const data = formatJson(filterVal, list)
                  export_json_to_excel.export_json_to_excel(tHeader, data, '样本数据表')
          };

          const getExcelTemplate=()=>{
            const tHeader = ['样本数据ID', '实验名称', '实验时间', '实验完成人', '实验文件']
            var data=[['2023-04-18 15:48:33', '1', '实验1', '张三', '实验1文件']]

            export_json_to_excel.export_json_to_excel(tHeader, data, '样本数据表模板')
            closeDialog2();
            ElMessage({
                type: 'success',
                message: '下载导入模板成功'
            })
          }
// =======================================以上为导出新增==============================================  



</script>

<style>
</style>
